import Model from './Model';
import Sequelize from 'sequelize';
import Bcrypt from 'bcrypt';

export default class User extends Model {
    constructor () {
        super('users', {
            id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
            name: Sequelize.STRING,
            email: Sequelize.STRING,
            password: Sequelize.STRING,
            avatar: Sequelize.STRING,
        }, {timestamps: false});
    }

    find (id) {
        return this.model.findAll({
            where: {
                id
            },
            attributes: ['id', 'name']
        });
    }

    async create (data) {
        if (data.password) {
            data = User.computePassword(data);
        }
        return await new Promise((resolve, reject) => {
            this.model.create(data).then(async user => {
                let data = await user.get();
                return resolve(data);
            }).catch(err => reject(err));
        });
    }

    static computePassword (data) {
        data.password = Bcrypt.hashSync(data.password, 10);
        return data;
    }
}
